//
//  MTWalletApiManager.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/19.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTWalletApiManager.h"
#import "MTValidationCodeController.h"
#import "YTKKeyValueStore.h"
#import "MTWalletViewController.h"
#import "MTRegisterViewController.h"
@interface MTWalletApiManager ()

@property(nonatomic,strong) YTKKeyValueStore *store;


@end


static MTWalletApiManager *walletapimanager = nil;
@implementation MTWalletApiManager


+(instancetype)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        walletapimanager = [[MTWalletApiManager alloc] init];
    });
    return walletapimanager;
}
-(YTKKeyValueStore *)store
{
    if(_store == nil)
    {
        _store = [[YTKKeyValueStore alloc] initDBWithName:MiTuCacheDBName];
        [_store createTableWithName:walletTableName];
    }
    return _store;
}
-(MTWalletInfo *)walletInfo
{
    if(_walletInfo == nil)
    {
         NSDictionary *dict = [self.store getObjectById:walletinfoKey fromTable:walletTableName];
         MTWalletInfo *model = [MTWalletInfo mj_objectWithKeyValues:dict];
        _walletInfo = model;
    }
    return _walletInfo;
}

-(void)pushSetPasswordVcFromVc:(UIViewController *)curentVc 
{
    
    UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:@"设置钱包密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([curentVc isKindOfClass:[MTWalletViewController class]])
        {
            [curentVc.navigationController popViewControllerAnimated:YES];
        }
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.fromVc = curentVc;
        MTUserModel *cureentModel = [MTUserModel currentUser];
        NSString *countryCode = cureentModel.countryCode;
        NSString *phone = cureentModel.phone;
        if(countryCode.length > 0 && phone.length > 0)
        {
            MTValidationCodeController *validationVc = [MTValidationCodeController baseStoryBordWithName:@"Login"];
            validationVc.phone = phone;
            validationVc.contryCode = countryCode;
            validationVc.validationCodeType = MTValidationCodeSetWalletPassword;
            validationVc.needRequstVerCode = YES;
            [self.fromVc.navigationController pushViewController:validationVc animated:YES];
        }else
        {
            MTRegisterViewController *registerVc = [MTRegisterViewController baseStoryBordWithName:@"Login"];
            registerVc.validationCodeType = MTValidationCodeSetWalletPassword;
            [self.fromVc.navigationController pushViewController:registerVc animated:YES];
        }
    }];
    [alterVc addAction:action1];
    [alterVc addAction:action2];
    [curentVc presentViewController:alterVc animated:YES completion:nil];
    
    
    
   
    
}

/**
 获取用户的币的列表
 
 @param completionBlock 完成block
 */
-(void)getUserCoinsWithcomplation:(void (^)(NSMutableArray<MTCoinModel *> *coins ,MTError *boerror))completionBlock
{
    [[MTHttpTool shareTool] getPath:@"/wallet/get_user_coins" parameters:nil success:^(MTBaseData *datamodel) {
        NSMutableArray *coins = [MTCoinModel mj_objectArrayWithKeyValuesArray:datamodel.data];
        self.coins = coins;
        completionBlock(coins,nil);
    } failer:^(MTError *error) {
         completionBlock(nil,error);
    }];
}



/**
 获取用户的钱包信息
 
 @param completionBlock 完成block
 */
-(void)getUserWalletInfoWithcomplation:(void (^)(MTWalletInfo *walletInfo ,MTError *mterror))completionBlock
{
    [[MTHttpTool shareTool] getPath:@"/wallet/info" parameters:nil success:^(MTBaseData *datamodel) {
        MTWalletInfo *info = [MTWalletInfo mj_objectWithKeyValues:datamodel.data];
        [self.store putObject:datamodel.data withId:walletinfoKey intoTable:walletTableName];
        self.walletInfo = info;
        completionBlock(info,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

/**
 获取钱包记录
 
 @param symobl symbol
 @param page 页数
 @param completionBlock 完成block
 */
-(void)getRecordsWithSymbol:(NSString *)symobl
                       page:(int)page
                 complation:(void (^)(MTCoinRecordsTotalModel *totalRecords ,MTError *boerror))completionBlock
{
    
    NSDictionary *param = @{@"page":@(page),@"symbol":symobl};
    [[MTHttpTool shareTool] getPath:@"/wallet/get_records" parameters:param success:^(MTBaseData *datamodel) {
        MTCoinRecordsTotalModel *info = [MTCoinRecordsTotalModel mj_objectWithKeyValues:datamodel.data];
        completionBlock(info,nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}
/**
 设置钱包密码
 
 @param password 密码
 @param phone 手机号
 @param code 验证吗
 @param countryCode 国家编码
 @param completionBlock 完成block
 */
-(void)setWalletWithPassword:(NSString *)password
                       phone:(NSString *)phone
                        code:(NSString *)code
                 countryCode:(NSString *)countryCode
                  complation:(void (^)(MTError *error))completionBlock
{
    
    [MBProgressHUD showProcessHud:@"" toView:nil];
    NSString *crypPassword =    [LTAESTool decryptAES:password key:passwordCrypkey kVector:passwordCrypInvterKey];
    
    NSDictionary *param = @{@"code":code,
                            @"countryCode":countryCode,
                            @"password":crypPassword,
                            @"phone":phone
                            };
    [[MTHttpTool shareTool] postPath:@"/wallet/set_password" parameters:param success:^(MTBaseData *datamodel) {
        [MTWalletApiManager manager].walletInfo.setPassword = YES;
        NSMutableDictionary *dict =    [MTWalletApiManager manager].walletInfo.mj_keyValues;
        [self.store putObject:dict withId:walletinfoKey intoTable:walletTableName];
        completionBlock(nil);
    } failer:completionBlock];
    
}


/**
 创建钱包 创建钱包
 
 @param symbol 符号
 @param targetUserId 目标userId
 @param value 大赏值
 @param workId 作品ID
 @param completionBlock 完成block
 */
-(void)createRewardWithSymbol:(NSString *)symbol
                 targetUserId:(NSString *)targetUserId
                        value:(NSString *)value
                       workId:(NSString *)workId
                   complation:(void (^)(NSString  *orderId ,MTError *boerror))completionBlock
{
     NSDictionary *param = @{@"symbol":@"MET",
                             @"targetUserId":targetUserId,
                             @"value":value,
                             @"workId":workId
                             };
    [[MTHttpTool shareTool] postPath:@"/order/create_reward" parameters:param success:^(MTBaseData *datamodel) {
        completionBlock(datamodel.data[@"orderId"],nil);
    } failer:^(MTError *error) {
        completionBlock(nil,error);
    }];
}

-(void)comfirmRewardWithorderId:(NSString *)orderId
                      passworld:(NSString *)passworld
                     complation:(void(^)(NSString *orderId, MTError *error))commplationBlock

{
    NSString *crypPassword =    [LTAESTool decryptAES:passworld key:passwordCrypkey kVector:passwordCrypInvterKey];
    NSDictionary *param = @{@"orderId":orderId,
                            @"password":crypPassword};
    [[MTHttpTool shareTool] postPath:@"/order/pay" parameters:param success:^(MTBaseData *datamodel) {
        commplationBlock(orderId,nil);
    } failer:^(MTError *error) {
        commplationBlock(nil,error);
    }];
}

/**
 获取充值汇率
 
 @param commplationBlock 完成block
 */
-(void)getRechargeRatecomplation:(void(^)(double rate, MTError *error))commplationBlock
{
    if(_rate > 0)
    {
        commplationBlock(_rate,nil);
        return;
    }
    [[MTHttpTool shareTool] getPath:@"/order/get_recharge_rate" parameters:nil success:^(MTBaseData *datamodel) {
        double rate = [datamodel.data doubleValue];
        self.rate = rate;
        commplationBlock(rate,nil);
    } failer:^(MTError *error) {
        commplationBlock(0.0,error);
    }];
}


/**
 创建支付订单

 @param symbol symbol
 @param value value
 @param complationBlock 完成block
 */
-(void)createRechargeWithSymbol:(NSString *)symbol
                          value:(NSString *)value
                     complation:(void(^)(MTPayOrderModel *payOrder, MTError *error))complationBlock

{
    NSDictionary *dict = @{@"symbol":symbol,@"value":value};
    [[MTHttpTool shareTool] postPath:@"/order/create_recharge" parameters:dict success:^(MTBaseData *datamodel) {
        MTPayOrderModel *model = [MTPayOrderModel mj_objectWithKeyValues:datamodel.data];
        complationBlock(model,nil);
    } failer:^(MTError *error) {
        complationBlock(nil,error);
    }];
    
}

@end
